import { existsSync, mkdirSync, createWriteStream, appendFile } from 'fs'
import { resolve } from 'path'
import dayjs from 'dayjs';

const statusMap = {
  0: "success",
  1: "error",
  100: "hasRegister",
  101: "checkJs",
  200: "上报后台",
  201: "被抽查",
  202: "未申报",
  203: "待检查",
};

export const reportLog = (status, content) => {
  const date = new Date();
  const name = dayjs(date).format("YYYYMMDD");

  status = statusMap[status] || status;

  // 创建目录
  let pmiLogDirname = `${resolve()}/pmiLogs`;
  if (!existsSync(pmiLogDirname)) {
    mkdirSync(pmiLogDirname);
  }

  // 按日期创建目录
  pmiLogDirname = `${pmiLogDirname}/${name}`;
  if (!existsSync(pmiLogDirname)) {
    mkdirSync(pmiLogDirname);
  }

  // 日志文件routes文件夹下，创建日志文件
  let path = `${pmiLogDirname}/${status}.log`;
  if (!existsSync(path)) {
    createWriteStream(path);
  }

  // 写入日志
  appendFile(path, JSON.stringify(content) + ",\n", function (err) {
    console.log("写入成功");
  });
};
